package com.dbutils.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcKit {

    /**
     * 获取连接池
     */
    public static ComboPooledDataSource ds = new ComboPooledDataSource();
    /**
     * 线程共享变量
     */
    public static ThreadLocal<Connection> container = new ThreadLocal<Connection>();

    /**
     * 获取线程变量
     *
     * @return
     */
    public static ThreadLocal<Connection> getContainer() {
        return container;
    }

    public static DataSource getDataSource() {
        return ds;
    }

    /**
     * 开启事务
     */
    public static void startTransaction() {
        Connection conn = container.get();
        if (conn == null) {
            conn = getConnection();
            container.set(conn);
        }
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 提交事务
     */
    public static void commit() {
        Connection conn = container.get();
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        Connection conn = container.get();
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        Connection conn = container.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            } finally {
                container.remove();
            }
        }
    }


    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }


}
